package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.remark.entity.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-23
 */
//@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;

    @Override
    public void addLikeRecord(LikeRecordFormDTO recordFormDTO) {
        //1.基于前端参数，判断是执行点赞还是取消点赞
        boolean isLike = recordFormDTO.getLiked() ? like(recordFormDTO) : unLike(recordFormDTO);

        //2.判断是否执行成功，如果失败，直接结束
        if (!isLike){
            return;
        }

        //3.如果执行成功，统计点赞数
        Integer likedTimes = lambdaQuery().eq(LikedRecord::getBizId, recordFormDTO.getBizId()).count();

        //4.发送MQ通知
        mqHelper.send(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, recordFormDTO.getBizType()),
                LikedTimesDTO.of(recordFormDTO.getBizId(),likedTimes)
        );
    }

    /**
     * 2、查询点赞记录
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        //1、获取登录用户ID
        Long userId = UserContext.getUser();
        //2、查询点赞记录
        List<LikedRecord> list = lambdaQuery()
                .in(LikedRecord::getBizId, bizIds)
                .eq(LikedRecord::getUserId, userId)
                .list();
        //3、返回已经点赞业务ID集合
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    @Override
    public void readLikeTimesAndSendMessage(String bizType, int maxBizSize) {

    }

    private boolean like(LikeRecordFormDTO recordFormDTO) {
        //1.查询点赞记录
        Integer count = lambdaQuery()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .eq(LikedRecord::getBizType, recordFormDTO.getBizId())
                .count();
        //2.判断是否存在，如果已经存在，直接结束，返回false
        if (count > 0){
            return false;
        }
        //3.如果不存在，新增点赞记录
        LikedRecord likeRecord = new LikedRecord();
        likeRecord.setUserId(UserContext.getUser());
        likeRecord.setBizId(recordFormDTO.getBizId());
        likeRecord.setBizType(recordFormDTO.getBizType());
        return save(likeRecord);
    }

    private boolean unLike(LikeRecordFormDTO recordFormDTO) {
        return remove(new LambdaQueryWrapper<LikedRecord>()
                .eq(LikedRecord::getUserId,UserContext.getUser())
                .eq(LikedRecord::getBizId,recordFormDTO.getBizId())
        );
    }

}
